package servlet;

import com.alibaba.fastjson.JSONObject;
import utils.VerifyCodeUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "VerifyCodeServlet", value = "/verifyCode")
public class VerifyCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");


        switch (method) {
            case "getCode"://1.获取验证码的图片
                getCode(request, response);
                break;
            case "checkCode"://2.对用户发来的的文本进行校验
                checkCode(request, response);
                break;
        }
    }

    //对用户发来的的文本进行校验
    private void checkCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        String verifyCodeInSession = (String) session.getAttribute("VERIFY_CODE");
        String verify = request.getParameter("verify");
        Map<String, String> resultMap = new HashMap();
        if (verifyCodeInSession != null && verifyCodeInSession.equals(verify)) {
            resultMap.put("result", "VERIFY_PASS");
        } else {
            resultMap.put("result", "VERIFY_FAIL");
        }
        Object o = JSONObject.toJSON(resultMap);
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(o);
    }

    //获取验证码的图片
    private void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        ServletOutputStream os = response.getOutputStream();
        String code = VerifyCodeUtil.outputVerifyImage(100, 40, os, 4);
        HttpSession session = request.getSession();
        session.setAttribute("VERIFY_CODE", code);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
